import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

import { ParkDataProvider } from '../../providers/park-data/park-data';
import { Park } from '../../providers/park-data/park';

import * as _ from "lodash";


// 声明高德地图对象AMap
declare var AMap: any;

@Component({
  selector: 'page-park-map',
  templateUrl: 'park-map.html',
})
export class ParkMapPage {
  @ViewChild('map_container') map_container:ElementRef;

  private map: any;
  private parks: Park[] = [];
  private markers: any[] = [];

  constructor(public navCtrl: NavController, 
    public navParams: NavParams,
    public parkDataProvider:ParkDataProvider) {
  }

  ionViewDidLoad() {
    this.initAMap();
    // this.setMarker();
    this.setData();
    this.setEvent();
  }

  initAMap(){
    this.map = new AMap.Map(this.map_container.nativeElement, {
      resizeEnable: true,
      zoom:11,//级别
      // center: [116.397428, 39.90923],//中心点坐标
      viewMode:'3D'//使用3D视图
  });

  // 加载插件
  AMap.plugin(['AMap.ToolBar','AMap.Geolocation'],() =>{
    this.map.addControl(new AMap.ToolBar());
    let geolocation = new AMap.Geolocation();
    geolocation.getCurrentPosition((status,result) => {

    });
    geolocation.getCityInfo((status,result) => {
      console.log(result);
      
    });
    this.map.addControl(geolocation);
  })
  }

  setMarker(parks: Park[]){
    // parks = parks.slice(0,10);
    // console.log(parks);
    

    parks.forEach(park => {
      let [lng,lat] = park.point.split(',');
      let marker = new AMap.Marker({
        position: new AMap.LngLat(lng, lat),   // 经纬度对象
        title: park.name,
        label: {content: park.name, offset: new AMap.Pixel(10,-5)}
      })
      this.markers.push(marker)
    });



    // let marker = new AMap.Marker({
    //     position: new AMap.LngLat(115.992811, 29.712034),   // 经纬度对象
    //     title: '测试数据',
    //     label: {content: 'label测试', offset: new AMap.Pixel(10,-5)}
    // })
    this.map.add(this.markers);

  }

  setData(){
    this.parks = [];
    this.parkDataProvider.getCount().toPromise()
      .then(total => {console.log(`记录总数：${total}`);
      return this.parkDataProvider.getAllParks(total).toPromise();
    })
    .then(data => {
      data.forEach(_parks => {
        this.parks = this.parks.concat(_parks);
      });
      console.log(`Parks集合大小: ${this.parks.length}`);
      
    })
    .then(() => {
      this.parks = _.filter(this.parks,(park: Park) => {
        let [lng,lat] = park.point.split(',');
        let _point = new AMap.LngLat(lng,lat);
        if(this.map.getBounds().contains(_point))
          return true;
      });
      console.log(`当前可视景区区域数: ${this.parks.length}`);
    })
    .then(() => {
      this.setMarker(this.parks);
    });
  }


  setEvent(){
    this.map.on('moveend',() => {this.setData();})
  }

}
